from sqlalchemy import desc
from src.common.logger import getLogger
from datetime import datetime, timedelta

logger = getLogger()

def select_user_list():
    from src.modules.home.model.user_model import User
    list = User.query.all()
    logger.info(f"user select_user_list list len: {len(list)}")
    result = [user.to_dict() for user in list]
    return result

def select_user_page(args):
    from ..model.user_model import User
    current_page = int(args.get("current_page", 0))
    page_size = int(args.get("page_size", 10))
    userName = args.get("userName", "")
    phoneNumber = args.get("phoneNumber", "")
    createTime = args.get("createTime", "")

    query = User.query
    total = query.count()
    pages = (total + page_size - 1) // page_size

    if userName:
        query = query.filter(User.user_name.like(f"%{userName}%"))
    if phoneNumber:
        query = query.filter(User.phone_number.like(f"%{phoneNumber}%"))
    if createTime:
        target_date = datetime.strptime(createTime, '%Y-%m-%d').date()
        start_date = datetime.combine(target_date, datetime.min.time())
        end_date = start_date + timedelta(days = 1)
        query = query.filter(User.create_time >= start_date, User.create_time < end_date)

    lists = []
    records = query.order_by(desc(User.create_time)).offset(current_page * page_size).limit(page_size).all()
    for record in records:
        item = record.to_dict()
        if item["create_time"]:
            item["create_time"] = item["create_time"].strftime('%Y-%m-%d %H:%M:%S')
        lists.append(item)
    return { "total": total, "pages": pages, "records": lists }

def add_user(user):
    from ... import db
    db.session.add(user)
    db.session.commit()

def update_user(user):
    from ... import db
    from ..model.user_model import User

    old_user = User.query.get(user.id)
    old_user.user_name = user.user_name
    old_user.password = user.password
    old_user.phone_number = user.phone_number
    old_user.email = user.email
    old_user.resume = user.resume
    old_user.photo = user.photo
    old_user.visit = user.visit
    db.session.commit()

def delete_user(user):
    from ... import db

    if user:
        db.session.delete(user)
        db.session.commit()

def select_system_user(args):
    from ..model.user_model import User

    user_name = args.get("user_name")
    password = args.get("password")

    query = User.query
    if user_name:
        query = query.filter(User.user_name == user_name)
    if password:
        query = query.filter(User.password == password)
    user = query.first()
    user = user.to_dict()
    user["create_time"] = user["create_time"].strftime('%Y-%m-%d %H:%M:%S')
    return user
